package com.changan.stumgr.controller;

import com.changan.stumgr.pojo.Grade;
import com.changan.stumgr.pojo.Student;
import com.changan.stumgr.service.StudentService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

//@ResponseBody+@Controller   返回Json格式
//@RestController
//restful风格  rest风格
@Controller
public class StudentController {

    @Autowired
    private StudentService studentService;

    /**
     * 获取数据使用GetMapping()
     * @return  是一个视图名称  /template/*.html
     */
    @GetMapping("/students{pageNum}")
    public String list(Model model, @PathVariable(value = "pageNum",required = false) Integer pageNum, String searchName, HttpSession session, HttpServletRequest request){
        PageInfo<Student> students = studentService.selAllStudent(pageNum,3,searchName);
        System.out.println(students.getPages());
        request.setAttribute("searchName",searchName);
        model.addAttribute("students",students);
        return "list";
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @RequestMapping("/DELETEStudent/{id}")
    public String delete(@PathVariable("id") Integer id){
        System.out.println(id+"------");
        studentService.delStudent(id);
        return "redirect:/students";
    }


    /**
     * 修改数据
     * @return
     */
    @RequestMapping("/modify")
    public String modify(Integer id,Model model) {
        System.out.println(id);
        if(id==null){//没有id值 进 新增页面
            return "forward:/show";
        }
        Student student=studentService.findByIdStudent(id);
        System.out.println(student.getGradeId()+" 老四");
           model.addAttribute("student",student);
        return "forward:/show";
    }

    /**
     * 保存
     * @param student
     * @return
     */
    @RequestMapping("/oksave")
    public String oksave(Student student) {
        if(student.getId()!=null){//没有id值就转发到新增
            return "forward:/updatesave";
        }
       studentService.addStudent(student);
        return "redirect:/students";
    }

    /***
     * 新增保存
     * @param student
     * @return
     */
    @RequestMapping("/updatesave")
    public String updatesave(Student student) {
        studentService.updateStudent(student);
        return "redirect:/students";
    }

}
